package com.hjs.juc;

/**
 * 1.jvm回为每一个线程分配独立的内存用来提高效率
 * 2.volatile: 当多个线程进行操作共享内存时，可以保证内存中的数据可见
 *
 * 注意：
 * 1.volatile不具有“互斥性”
 * 2.volatile不能保证原子性
 *
 *
 * @author hanjinsong
 * @date 2020-02-19 10:05
 */
public class TestVolatile {

    public static void main(String[] args) {
        ThreadDemo threadDemo = new ThreadDemo();
        new Thread(threadDemo).start();

        while (true) {
            if (threadDemo.isFlag()) {
                System.out.println("***********");
                break;
            }
        }
        //加锁，效率低
        while (true) {
            synchronized (threadDemo) {
                if (threadDemo.isFlag()) {
                    System.out.println("---------------");
                    break;
                }
            }
        }
    }

}
class ThreadDemo implements Runnable {

    //private boolean flag = false;
    private volatile boolean flag = false;

    @Override
    public void run() {
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        flag = true;
        System.out.println("flag:" + flag);
    }

    public boolean isFlag() {
        return flag;
    }

    public void setFlag(boolean flag) {
        this.flag = flag;
    }
}
